//
//  CHMainController.swift
//  status
//
//  Created by 彳亍 on 2017/3/22.
//  Copyright © 2017年 彳亍. All rights reserved.
//

import UIKit

class CHMainController: UITabBarController {
    
    /// 撰写按钮
    lazy var composeButton:CHComposeButton = CHComposeButton()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 1. 设置子控制器
        setupChildControllers()
        // 2. 设置撰写按钮
        setupComposeButton()
        // 3. 注册通知
        registerNotifications()
        // 4. 设置新特性
        setupNewFeature()
    }
    
    deinit {
        // 1. 移除通知
        removeNotifications()
    }
    
}

// MARK: - 通知
extension CHMainController {
    /// 注册通知
    fileprivate func registerNotifications() {
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(userRegisterNotifacation),
                                               name: NSNotification.Name(rawValue: CHUserRegisterNotification),
                                               object: nil)
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(userLoginNotification),
                                               name: NSNotification.Name(rawValue: CHUserLoginNotification),
                                               object: nil)
        
    }
    
    /// 移除通知
    fileprivate func removeNotifications() {
        NotificationCenter.default.removeObserver(self)
    }
    
    /// 用户登录通知
    @objc fileprivate func userLoginNotification() {
        showOAuthController()
    }
    
    /// 用户注册通知
    @objc fileprivate func userRegisterNotifacation() {
        showOAuthController()
    }
    
    /// 展示授权控制器
    private func showOAuthController() {
        let OAuthVC = CHOAuthController()
        present(UINavigationController(rootViewController:OAuthVC), animated: true, completion: nil)
    }
    
    
}


// MARK: - UI
extension CHMainController {
    /// 设置撰写按钮
    fileprivate func setupComposeButton() {
        // 1. 添加撰写按钮
        tabBar.addSubview(composeButton)
        // 2. 设置位置
        guard let count = viewControllers?.count else {return}
        let item_w = tabBar.bounds.width / CGFloat(count)
        composeButton.frame = tabBar.bounds.insetBy(dx: item_w * 2, dy: 0)
        
    }
    
    /// 设置新特性
    fileprivate func setupNewFeature() {
        let isNotFirstInstall = UserDefaults.standard.bool(forKey: CHUserNotFirstInstallKey)
        
        isNotFirstInstall && CHHTTPSessionManager.shared.logan  ? setupWelcomeView() : setupNewFeatureView()

    }
    
    /// 设置新特性页
    private func setupNewFeatureView() {
        let newFeatureView = CHNewFeatureView(frame: UIScreen.main.bounds)
        view.addSubview(newFeatureView)
    }
    
    /// 设置欢迎页
    private func setupWelcomeView() {
        let welcomeView = CHWelcomeView(frame: UIScreen.main.bounds)
        view.addSubview(welcomeView)
    }
    
    
}


// MARK: - 设置子控制器
extension CHMainController {
    
    /// 设置子控制器
    fileprivate func setupChildControllers() {
        // 1. 文件名称
        let fileName = "main.json"
        // 2. 加载数据
        var data = NSData(contentsOfFile: String.ch_sandboxDir(fileName: fileName))
        // 3. 如果没有数据 则从bundle加载
        if data == nil {
            data = NSData(contentsOfFile: String.ch_bundleDir(fileName: fileName))
        }
        // 4. 数据反序列化
        guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String:AnyObject]] else {
            return
        }
        // 5. 便利数组
        var childControllers = [UIViewController]()
        for dict in array ?? [] {
            childControllers.append(controller(dict: dict))
        }
        // 6. 设置控制器
        viewControllers = childControllers
    }
    
    /// 创建控制器
    ///
    /// - Parameter dict: 参数字典
    private func controller(dict:[String:AnyObject]) ->UIViewController {
        // 1.获取参数数据
        guard let clsName = dict["clsName"] as? String,
            let cls = NSClassFromString(Bundle.main.ch_namespace + "." + clsName) as? CHViewController.Type,
            let title = dict["title"] as? String,
            let visitorInfo = dict["visitorInfo"] as? [String : String],
            let imageName = dict["imageName"] as? String
            
            else {
                return UIViewController()
        }
        
        // 2.创建控制器
        let vc = cls.init()
        vc.title = title
        vc.visitorInfo = visitorInfo
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)?.withRenderingMode(.alwaysOriginal)
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.black], for: UIControlState.normal)
        
        return CHNavigationController(rootViewController: vc)
    }
    
}
